<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>监室管理系统 - {{ room_number }}号监室</title>
    <style>
        :root {
            --primary-color: #2c3e50;
            --secondary-color: #3498db;
            --accent-color: #8bc34a;
            --background: #ff7fa;
            --card-bg: #ffffff;
            --border-color: #e1e4e8;
        }

        * {
            box-sizing: border-box;
            margin: 0;
            padding: 0;
        }

        body {
            margin: 0;
            padding: 20px;
            min-height: 100vh;
            display: flex;
            justify-content: center;
            align-items: center;
            background: var(--background);
            font-family: 'Segoe UI', 'Microsoft YaHei', sans-serif;
        }

        .room-header {
            grid-row: 1 / 2;
            grid-column: 1 / -1;
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 15px;
            padding: 0 10px;
        }

        .room-title {
            color: var(--primary-color);
            font-size: 1.8rem;
            font-weight: 600;
        }

        .room-info {
            background: #e3f2fd;
            padding: 8px 15px;
            border-radius: 20px;
            font-size: 1rem;
            color: #1976d2;
        }

        .room-container {
            width: 95%;
            max-width: 1100px;
            min-height: calc(100vh - 40px);
            height: auto;
            display: grid;
            grid-template-columns: repeat(2, 1fr);
            grid-template-rows: auto 1fr 1fr;
            gap: 25px;
            box-shadow: 0 10px 30px rgba(0,0,0,0.08);
            background: var(--card-bg);
            border-radius: 15px;
            padding: 25px;
            position: relative;
            overflow-y: auto;
        }

        .home-btn {
            position: absolute;
            bottom: 20px;
            right: 20px;
            padding: 12px 24px;
            background: linear-gradient(135deg, #3498db, #2980b9);
            color: white;
            border: none;
            border-radius: 30px;
            font-size: 1.1rem;
            font-weight: 600;
            cursor: pointer;
            box-shadow: 0 4px 12px rgba(0,0,0,0.15);
            transition: all 0.3s ease;
            z-index: 100;
        }

        .home-btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 6px 15px rgba(0,0,0,0.2);
            background: linear-gradient(135deg, #2980b9, #3498db);
        }

        .seat-section {
            position: relative;
            grid-row: 2 / 3;
            grid-column: 1 / 2;
            border: 2px solid #ffd54f;
            border-radius: 12px;
            padding: 15px;
            box-shadow: 0 4px 12px rgba(0,0,0,0.05);
            background-color: #fff8e1;
            display: flex;
            flex-direction: column;
        }

        .section-header {
            position: absolute;
            top: -12px;
            left: 20px;
            background: #ffd54f;
            color: #2c3e50;
            padding: 5px 15px;
            border-radius: 6px;
            font-weight: bold;
            font-size: 1.1rem;
            z-index: 10;
            box-shadow: 0 2px 6px rgba(0,0,0,0.1);
        }

        .seat {
            display: grid;
            grid-template-columns: 60% 20% 20%;
            grid-template-rows: 20% 80%;
            height: 100%;
            position: relative;
            overflow: visible;
        }

        .bed-section {
            position: relative;
            grid-row: 2 / 3;
            grid-column: 2 / 3;
            border: 2px solid #64b5f6;
            border-radius: 12px;
            padding: 15px;
            box-shadow: 0 4px 12px rgba(0,0,0,0.05);
            background-color: #e3f2fd;
            display: flex;
            flex-direction: column;
        }

        .bed {
            display: grid;
            grid-template-columns: 50% 50%;
            grid-template-rows: 20% 80%;
            height: 100%;
            position: relative;
            overflow: visible;
        }

        .schedule-section {
            position: relative;
            grid-row: 3 / 4;
            grid-column: 1 / 3;
            background: var(--card-bg);
            border: 2px solid var(--accent-color);
            border-radius: 12px;
            padding: 30px 20px 20px;
            display: flex;
            flex-direction: column;
            box-shadow: 0 4px 12px rgba(0,0,0,0.05);
        }

        .schedule-header {
            position: absolute;
            top: -12px;
            left: 20px;
            background: var(--accent-color);
            color: #2c3e50;
            padding: 5px 15px;
            border-radius: 6px;
            font-weight: bold;
            font-size: 1.1rem;
            z-index: 10;
            box-shadow: 0 2px 6px rgba(0,0,0,0.1);
        }

        .area {
            border: 1px solid rgba(0,0,0,0.15);
            padding: 12px;
            box-sizing: border-box;
            position: relative;
            border-radius: 8px;
            background-clip: padding-box;
            box-shadow: inset 0 2px 4px rgba(0,0,0,0.03);
        }

        .area::before {
            content: attr(data-name);
            display: block;
            font-family: Arial;
            font-size: 0.9em;
            color: #555;
            padding: 3px 8px;
            background: rgba(255,255,255,0.85);
            border-radius: 4px;
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            font-weight: 500;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
            white-space: nowrap;
        }

        .seat .area::before {
            font-size: 0.85em;
            padding: 3px 6px;
        }

        .wash-area {
            grid-column: 1;
            grid-row: 1;
            background: #e3f2fd;
        }

        .seat1-area {
            grid-column: 1;
            grid-row: 2;
            background: #fff8e1;
            display: grid;
            grid-template-columns: repeat(3, minmax(0, 1fr));
            grid-template-rows: repeat(9, minmax(0, 1fr));
            gap: 4px;
        }

        .cell {
            border: 1px solid #e0e0e0;
            min-height: 20px;
            min-width: 30px;
            background-color: #ffffff;
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            font-size: 0.75em;
            color: #444;
            line-height: 1.4;
            padding: 6px 2px;
            text-align: center;
            border-radius: 4px;
            overflow: hidden;
        }

        .cell-content {
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            width: 100%;
            height: 100%;
        }

        .cell-name {
            font-size: 0.8em;
            font-weight: 600;
            margin-bottom: 2px;
            line-height: 1.2;
        }

        .cell-date {
            font-size: 0.65em;
            color: #666;
        }

        .empty-cell .cell-name,
        .empty-cell .cell-date {
            color: #999;
            font-style: italic;
        }

        .tunnel-area {
            grid-column: 2;
            grid-row: 1 / 3;
            background: #f5f5f5;
        }

        .box-area {
            grid-column: 3;
            grid-row: 1;
            background: #fce4ec;
        }

        .seat2-area {
            grid-column: 3;
            grid-row: 2;
            background: #e0f7fa;
            display: grid;
            grid-template-columns: repeat(1, minmax(0, 1fr));
            grid-template-rows: repeat(9, minmax(0, 1fr));
            gap: 4px;
        }

        .bed-wash-area {
            grid-column: 1;
            grid-row: 1;
            background: #e3f2fd;
        }

        .bed1-area {
            grid-column: 1;
            grid-row: 2;
            background: #fff8e1;
            display: grid;
            grid-template-columns: repeat(1, minmax(0, 1fr));
            grid-template-rows: repeat(13, minmax(0, 1fr));
            gap: 4px;
        }

        .bed2-area {
            grid-column: 2;
            grid-row: 1;
            background: #fff8e1;
            display: grid;
            grid-template-columns: repeat(1, minmax(0, 1fr));
            grid-template-rows: repeat(3, 1fr);
            gap: 4px;
            padding: 8px 10px;
        }

        .bed3-area {
            grid-column: 2;
            grid-row: 2;
            background: #fff8e1;
            display: grid;
            grid-template-columns: repeat(3, minmax(0, 1fr));
            grid-template-rows: repeat(4, minmax(0, 1fr));
            gap: 4px;
        }

        .schedule-container {
            display: grid;
            grid-template-rows: 1fr auto auto;
            height: 100%;
            gap: 15px;
            padding: 15px;
            box-sizing: border-box;
        }

        .schedule-table-container {
            overflow-y: auto;
            min-height: 0;
        }

        .schedule-table {
            width: 100%;
            border-collapse: collapse;
            border-spacing: 0;
            font-size: 0.95rem;
            table-layout: fixed;
            flex-grow: 1;
            overflow: auto;
            border-radius: 8px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.08);
        }

        .schedule-table thead {
            background: linear-gradient(to bottom, #3a506b, #2c3e50);
            color: white;
            position: sticky;
            top: 0;
            z-index: 10;
        }

        .schedule-table th {
            padding: 14px 8px;
            text-align: center;
            font-weight: 500;
            border-right: 1px solid #4a6180;
            font-size: 0.98rem;
            min-width: 90px;
        }

        .schedule-table th:first-child {
            border-top-left-radius: 8px;
        }

        .schedule-table th:last-child {
            border-top-right-radius: 8px;
            border-right: none;
        }

        .schedule-table tbody {
            width: 100%;
        }

        .schedule-table td {
            padding: 12px 8px;
            text-align: center;
            border-bottom: 1px solid #e0e0e0;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
        }

        .shift-cell {
            background: linear-gradient(to right, #f0f4f8, #e3ebf3);
            font-weight: 600;
            color: #2c3e50;
            padding: 12px 8px;
            text-align: center;
            border-right: 1px solid #e0e0e0;
            position: sticky;
            left: 0;
            z-index: 5;
            font-size: 0.95rem;
            width: 100px;
        }

        .data-cell {
            padding: 10px 6px;
            text-align: center;
            border-right: 1px solid #e0e0e0;
            border-bottom: 1px solid #e0e0e0;
            background-color: #ffffff;
            transition: background 0.2s ease;
            font-size: 0.92rem;
            height: 70px;
            vertical-align: top;
        }

        .person-container {
            display: flex;
            flex-direction: column;
            justify-content: center;
            height: 100%;
            min-height: 60px;
        }

        .person-name {
            font-size: 1em;
            padding: 4px 0;
            margin: 2px 0;
            flex-grow: 1;
            display: flex;
            align-items: center;
            justify-content: center;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
        }

        .person-name:first-child {
            border-bottom: 1px dashed #e0e0e0;
        }

        .shift-row:nth-child(odd) .data-cell {
            background-color: #f9f9f9;
        }

        .shift-row:nth-child(even) .data-cell {
            background-color: #ffffff;
        }

        .shift-row:hover .data-cell {
            background-color: #f0f7ff !important;
        }

        .data-cell:last-child, .shift-cell:last-child {
            border-right: none;
        }

        .schedule-note {
            margin-top: 15px;
            padding: 12px 15px;
            background: linear-gradient(to right, #e8f5e9, #d7eeda);
            border-radius: 8px;
            font-size: 0.92rem;
            color: #2e7d32;
            border-left: 4px solid #4caf50;
            box-shadow: 0 2px 5px rgba(0,0,0,0.05);
        }

        .empty-slot {
            color: #9e9e9e;
            font-style: italic;
        }

        .schedule-actions {
            margin-top: 15px;
            display: flex;
            gap: 10px;
        }

        .schedule-btn {
            padding: 8px 15px;
            background-color: #3498db;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 0.9rem;
            transition: background-color 0.2s;
        }

        .schedule-btn:hover {
            background-color: #2980b9;
        }

        .schedule-btn.save {
            background-color: #2ecc71;
        }

        .schedule-btn.save:hover {
            background: #27ae60;
        }

        .schedule-btn.regenerate {
            background-color: #e74c3c;
        }

        .schedule-btn.regenerate:hover {
            background-color: #c0392b;
        }

        .schedule-btn.simulate {
            background-color: #9b59b6;
        }

        .schedule-btn.simulate:hover {
            background-color: #8e44ad;
        }

        .week-selector {
            display: flex;
            align-items: center;
            gap: 10px;
            margin-left: 20px;
        }

        #week-select {
            padding: 8px 15px;
            border-radius: 5px;
            border: 1px solid #ddd;
            background-color: white;
            font-size: 16px;
        }

        .schedule-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .query-btn {
            padding: 8px 15px;
            background-color: #f39c12;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 0.9rem;
            transition: background-color 0.2s;
        }

        .query-btn:hover {
            background-color: #e67e22;
        }

        .layout-actions {
            margin-top: 10px;
            display: flex;
            gap: 10px;
            justify-content: center;
        }

        .layout-btn {
            padding: 6px 12px;
            background-color: #3498db;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 0.85rem;
            transition: background-color 0.2s;
        }

        .layout-btn:hover {
            background-color: #2980b9;
        }

        .layout-btn.save {
            background-color: #2ecc71;
        }

        .layout-btn.save:hover {
            background-color: #27ae60;
        }

        .layout-btn.regenerate {
            background-color: #e74c3c;
        }

        .layout-btn.regenerate:hover {
            background-color: #c0392b;
        }

        @media (max-width: 1200px) {
            .schedule-table th,
            .shift-cell,
            .data-cell {
                font-size: 0.88rem;
                padding: 10px 6px;
            }

            .person-name {
                font-size: 0.85em;
            }

            .bed2-area {
                padding: 4px 6px;
            }
        }

        .bed2-area .cell {
            font-size: 0.7em;
            padding: 3px;
        }
    </style>
</head>
<body>
    <div class="room-container">
        <div class="room-header">
            <div class="room-title">{{ room_number }}号监室</div>
            <div class="room-info">总人数: {{ total }}人</div>
        </div>

        <!-- 座位区 -->
        <div class="seat-section">
            <div class="section-header">座位表</div>
            <div class="seat">
                <div class="area wash-area" data-name="卫生区"></div>
                <div class="area seat1-area" id="seat1-area"></div>
                <div class="area tunnel-area" data-name="过道"></div>
                <div class="area box-area" data-name="储物区"></div>
                <div class="area seat2-area" id="seat2-area"></div>
            </div>
            <div class="layout-actions">
                {% if not seatdata_exists %}
                    <button id="generate-seat-btn" class="layout-btn">生成座位</button>
                {% else %}
                    <button id="regenerate-seat-btn" class="layout-btn regenerate">重新生成</button>
                    <button id="save-seat-btn" class="layout-btn save">存档</button>
                {% endif %}
            </div>
        </div>

        <!-- 铺位区 -->
        <div class="bed-section">
            <div class="section-header">铺位表</div>
            <div class="bed">
                <div class="area bed-wash-area" data-name="卫生区"></div>
                <div class="area bed1-area" id="bed1-area"></div>
                <div class="area bed2-area" id="bed2-area"></div>
                <div class="area bed3-area" id="bed3-area"></div>
            </div>
            <div class="layout-actions">
                {% if not beddata_exists %}
                    <button id="generate-bed-btn" class="layout-btn">生成铺位</button>
                {% else %}
                    <button id="regenerate-bed-btn" class="layout-btn regenerate">重新生成</button>
                    <button id="save-bed-btn" class="layout-btn save">存档</button>
                {% endif %}
            </div>
        </div>

        <!-- 排班表区 -->
        <div class="schedule-section">
            <div class="schedule-header">
                <div class="schedule-title">值班安排表</div>
                <div class="schedule-controls">
                    <div class="week-selector">
                        <select id="week-select">
                            {% for option in week_options %}
                                <option value="{{ option.value }}" {% if option.is_current %}selected{% endif %}>
                                    {{ option.label }}{% if option.is_current %} (本周){% endif %}
                                </option>
                            {% endfor %}
                        </select>
                        <button id="week-query-btn" class="query-btn">查询</button>
                    </div>
                </div>
            </div>
            <div class="schedule-container">
                <div class="schedule-table-container">
                    <table class="schedule-table">
                        <thead>
                            <tr>
                                <th>班次</th>
                                <th>周一</th>
                                <th>周二</th>
                                <th>周三</th>
                                <th>周四</th>
                                <th>周五</th>
                                <th>周六</th>
                                <th>周日</th>
                            </tr>
                        </thead>
                        <tbody>
                            <tr class="shift-row">
                                <td class="shift-cell">午班<br>(12:00-13:30)</td>
                                {% for day in schedule %}
                                <td class="data-cell">
                                    <div class="person-container">
                                        {% for person in day.shifts.午班 %}
                                            <div class="person-name">{{ person.name }}</div>
                                        {% else %}
                                            <div class="person-name empty-slot">(空)</div>
                                            <div class="person-name empty-slot">(空)</div>
                                        {% endfor %}
                                    </div>
                                </td>
                                {% endfor %}
                            </tr>
                            <tr class="shift-row">
                                <td class="shift-cell">夜班1<br>(21:30-00:30)</td>
                                {% for day in schedule %}
                                <td class="data-cell">
                                    <div class="person-container">
                                        {% for person in day.shifts.夜班1 %}
                                            <div class="person-name">{{ person.name }}</div>
                                        {% else %}
                                            <div class="person-name empty-slot">(空)</div>
                                            <div class="person-name empty-slot">(空)</div>
                                        {% endfor %}
                                    </div>
                                </td>
                                {% endfor %}
                            </tr>
                            <tr class="shift-row">
                                <td class="shift-cell">夜班2<br>(00:30-03:30)</td>
                                {% for day in schedule %}
                                <td class="data-cell">
                                    <div class="person-container">
                                        {% for person in day.shifts.夜班2 %}
                                            <div class="person-name">{{ person.name }}</div>
                                        {% else %}
                                            <div class="person-name empty-slot">(空)</div>
                                            <div class="person-name empty-slot">(空)</div>
                                        {% endfor %}
                                    </div>
                                </td>
                                {% endfor %}
                            </tr>
                            <tr class="shift-row">
                                <td class="shift-cell">夜班3<br>(03:30-06:30)</td>
                                {% for day in schedule %}
                                <td class="data-cell">
                                    <div class="person-container">
                                        {% for person in day.shifts.夜班3 %}
                                            <div class="person-name">{{ person.name }}</div>
                                        {% else %}
                                            <div class="person-name empty-slot">(空)</div>
                                            <div class="person-name empty-slot">(空)</div>
                                        {% endfor %}
                                    </div>
                                </td>
                                {% endfor %}
                            </tr>
                        </tbody>
                    </table>
                </div>
                <div class="schedule-note">
                    <strong>值班规则说明：</strong>
                    1. 每班次安排2人值班；
                    2. 值班人员按入所时间顺序轮转；
                    3. 完成一轮值班后不再安排相同班次；
                    4. 人员变动后系统自动更新排班
                </div>
                <div class="schedule-actions">
                    {% if not schedule_exists %}
                        <button id="generate-btn" class="schedule-btn">生成当周值班表</button>
                    {% else %}
                        <button id="regenerate-btn" class="schedule-btn regenerate">重新生成</button>
                        <button id="save-btn" class="schedule-btn save">存档</button>
                    {% endif %}
                    <button id="simulate-btn" class="schedule-btn simulate">模拟测试</button>
                    <button class="home-btn" onclick="window.location.href='/'">回到首页</button>
                </div>
            </div>
        </div>
    </div>

    <script>
        // 数据初始化
        const backendData = {{ data|tojson }};
        const backendBedData = {{ beddata|tojson }};
        const backendSeatData = {{ seatdata|tojson }};
        const backendSchedule = {{ schedule|tojson }};
        const roomNumber = "{{ room_number }}";
        const beddataExists = {{ beddata_exists|tojson }};
        const seatdataExists = {{ seatdata_exists|tojson }};
        const scheduleExists = {{ schedule_exists|tojson }};
        const weekOptions = {{ week_options|tojson }};
        const selectedWeek = "{{ selected_week }}";
        const currentWeekMonday = "{{ current_week_monday }}";

        // 铺位和座位布局数据
        let bedLayoutData = backendBedData || [];
        let seatLayoutData = backendSeatData || [];

        // 渲染铺位和座位布局
        function renderLayouts() {
            renderBedLayout();
            renderSeatLayout();
        }

        // 渲染铺位布局
        function renderBedLayout() {
            const bed1Area = document.getElementById('bed1-area');
            const bed2Area = document.getElementById('bed2-area');
            const bed3Area = document.getElementById('bed3-area');

            if (!bed1Area || !bed2Area || !bed3Area) return;

            // 清空现有内容
            bed1Area.innerHTML = '';
            bed2Area.innerHTML = '';
            bed3Area.innerHTML = '';

            // 渲染铺位1-13
            for (let i = 0; i < 13; i++) {
                const cell = createLayoutCell(i, bedLayoutData);
                bed1Area.appendChild(cell);
            }

            // 渲染铺位14-25
            for (let i = 13; i < 25; i++) {
                const cell = createLayoutCell(i, bedLayoutData);
                bed3Area.appendChild(cell);
            }

            // 渲染铺位26+
            for (let i = 25; i < Math.min(bedLayoutData.length, 28); i++) {
                const cell = createLayoutCell(i, bedLayoutData);
                bed2Area.appendChild(cell);
            }
        }

        // 渲染座位布局
        function renderSeatLayout() {
            const seat1Area = document.getElementById('seat1-area');
            const seat2Area = document.getElementById('seat2-area');

            if (!seat1Area || !seat2Area) return;

            // 清空现有内容
            seat1Area.innerHTML = '';
            seat2Area.innerHTML = '';

            // 渲染座位1-27
            for (let i = 0; i < 27; i++) {
                const cell = createLayoutCell(i, seatLayoutData);
                seat1Area.appendChild(cell);
            }

            // 渲染座位28+
            for (let i = 27; i < Math.min(seatLayoutData.length, 36); i++) {
                const cell = createLayoutCell(i, seatLayoutData);
                seat2Area.appendChild(cell);
            }
        }

        // 创建布局单元格
        function createLayoutCell(index, data) {
            const cell = document.createElement('div');
            cell.className = 'cell';

            const cellContent = document.createElement('div');
            cellContent.className = 'cell-content';

            const nameDiv = document.createElement('div');
            nameDiv.className = 'cell-name';

            const dateDiv = document.createElement('div');
            dateDiv.className = 'cell-date';

            if (index < data.length && data[index]) {
                nameDiv.textContent = `${index + 1}. ${data[index].name}`;
                dateDiv.textContent = formatDate(data[index].join_date);
            } else {
                nameDiv.textContent = '空位';
                dateDiv.textContent = '-';
                cell.classList.add('empty-cell');
            }

            cellContent.appendChild(nameDiv);
            cellContent.appendChild(dateDiv);
            cell.appendChild(cellContent);

            return cell;
        }

        // 日期格式化
        function formatDate(dateString) {
            if (!dateString) return '无日期';
            try {
                const date = new Date(dateString);
                return date.toLocaleDateString('zh-CN', {
                    year: 'numeric',
                    month: '2-digit',
                    day: '2-digit'
                }).replace(/\//g, '-');
            } catch (e) {
                console.error('日期格式错误:', dateString, e);
                return '无效日期';
            }
        }

        // 生成铺位布局
        async function generateBedLayout() {
            // 按入所日期排序
            const sortedData = [...backendData].sort((a, b) =>
                new Date(a.join_date) - new Date(b.join_date));

            // 生成铺位布局数据
            bedLayoutData = sortedData.map((person, index) => ({
                id: person.id,
                name: person.name,
                join_date: person.join_date,
                position: `铺位${index + 1}`
            }));

            // 渲染新布局
            renderBedLayout();

            // 立即保存到数据库
            await saveBedLayout();
        }

        // 生成座位布局
        async function generateSeatLayout() {
            // 按入所日期排序
            const sortedData = [...backendData].sort((a, b) =>
                new Date(a.join_date) - new Date(b.join_date));

            // 生成座位布局数据
            seatLayoutData = sortedData.map((person, index) => ({
                id: person.id,
                name: person.name,
                join_date: person.join_date,
                position: `座位${index + 1}`
            }));

            // 渲染新布局
            renderSeatLayout();

            // 立即保存到数据库
            await saveSeatLayout();
        }

        // 保存铺位布局
        async function saveBedLayout() {
            try {
                const response = await fetch(`/save_bed_layout/${roomNumber}`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                        bed_data: bedLayoutData,
                        target_date: selectedWeek
                    })
                });

                const result = await response.json();
                if (result.success) {
                    alert('铺位保存成功!');
                    // 刷新页面
                    location.reload();
                } else {
                    alert('铺位保存失败');
                }
            } catch (error) {
                console.error('保存铺位错误:', error);
                alert('保存铺位时发生错误');
            }
        }

        // 保存座位布局
        async function saveSeatLayout() {
            try {
                const response = await fetch(`/save_seat_layout/${roomNumber}`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                        seat_data: seatLayoutData,
                        target_date: selectedWeek
                    })
                });

                const result = await response.json();
                if (result.success) {
                    alert('座位保存成功!');
                    // 刷新页面
                    location.reload();
                } else {
                    alert('座位保存失败');
                }
            } catch (error) {
                console.error('保存座位错误:', error);
                alert('保存座位时发生错误');
            }
        }

        // 页面加载时初始化布局
        document.addEventListener('DOMContentLoaded', () => {
            renderLayouts();

            // 绑定铺位生成按钮事件
            document.getElementById('generate-bed-btn')?.addEventListener('click', generateBedLayout);

            // 绑定铺位重新生成按钮事件
            document.getElementById('regenerate-bed-btn')?.addEventListener('click', generateBedLayout);

            // 绑定铺位存档按钮事件
            document.getElementById('save-bed-btn')?.addEventListener('click', saveBedLayout);

            // 绑定座位生成按钮事件
            document.getElementById('generate-seat-btn')?.addEventListener('click', generateSeatLayout);

            // 绑定座位重新生成按钮事件
            document.getElementById('regenerate-seat-btn')?.addEventListener('click', generateSeatLayout);

            // 绑定座位存档按钮事件
            document.getElementById('save-seat-btn')?.addEventListener('click', saveSeatLayout);

            // 周查询按钮事件
            document.getElementById('week-query-btn')?.addEventListener('click', function() {
                const selectedWeek = document.getElementById('week-select').value;
                const url = new URL(window.location.href);

                if (selectedWeek === currentWeekMonday) {
                    url.searchParams.delete('week');
                } else {
                    url.searchParams.set('week', selectedWeek);
                }

                window.location.href = url.toString();
            });

            // 值班表生成按钮事件
            document.getElementById('generate-btn')?.addEventListener('click', async function() {
                try {
                    const response = await fetch(`/generate_schedule/${roomNumber}`, {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json'
                        },
                        body: JSON.stringify({
                            target_date: selectedWeek
                        })
                    });

                    const result = await response.json();
                    if (result.success) {
                        // 立即保存新生成的排班表到数据库
                        const saveResponse = await fetch(`/save_schedule/${roomNumber}`, {
                            method: 'POST',
                            headers: {
                                'Content-Type': 'application/json'
                            },
                            body: JSON.stringify({
                                schedule: result.schedule,
                                target_date: selectedWeek
                            })
                        });

                        const saveResult = await saveResponse.json();
                        if (saveResult.success) {
                            // 刷新页面显示新值班表
                            location.reload();
                        } else {
                            alert('保存值班表失败');
                        }
                    } else {
                        alert('生成值班表失败');
                    }
                } catch (error) {
                    console.error('生成值班表错误:', error);
                    alert('生成值班表时发生错误');
                }
            });

            // 值班表重新生成按钮事件
            document.getElementById('regenerate-btn')?.addEventListener('click', async function() {
                try {
                    const response = await fetch(`/generate_schedule/${roomNumber}`, {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json'
                        },
                        body: JSON.stringify({
                            target_date: selectedWeek
                        })
                    });

                    const result = await response.json();
                    if (result.success) {
                        // 立即保存新生成的排班表到数据库
                        const saveResponse = await fetch(`/save_schedule/${roomNumber}`, {
                            method: 'POST',
                            headers: {
                                'Content-Type': 'application/json'
                            },
                            body: JSON.stringify({
                                schedule: result.schedule,
                                target_date: selectedWeek
                            })
                        });

                        const saveResult = await saveResponse.json();
                        if (saveResult.success) {
                            // 刷新页面显示新值班表
                            location.reload();
                        } else {
                            alert('保存值班表失败');
                        }
                    } else {
                        alert('重新生成值班表失败');
                    }
                } catch (error) {
                    console.error('重新生成错误:', error);
                    alert('重新生成值班表时发生错误');
                }
            });

            // 值班表存档按钮事件
            document.getElementById('save-btn')?.addEventListener('click', async function() {
                try {
                    const response = await fetch(`/save_schedule/${roomNumber}`, {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json'
                        },
                        body: JSON.stringify({
                            schedule: backendSchedule,
                            target_date: selectedWeek
                        })
                    });

                    const result = await response.json();
                    if (result.success) {
                        alert('值班表保存成功');
                    } else {
                        alert('值班表保存失败');
                    }
                } catch (error) {
                    console.error('保存错误:', error);
                    alert('保存值班表时发生错误');
                }
            });

            // 模拟测试按钮事件
            document.getElementById('simulate-btn')?.addEventListener('click', async function() {
                // 弹出对话框让用户选择日期
                const targetDate = prompt("请输入要模拟的日期 (YYYY-MM-DD格式):", selectedWeek);

                if (targetDate) {
                    try {
                        // 请求模拟排班
                        const response = await fetch(`/generate_schedule/${roomNumber}`, {
                            method: 'POST',
                            headers: {
                                'Content-Type': 'application/json'
                            },
                            body: JSON.stringify({
                                target_date: targetDate,
                                simulate: true
                            })
                        });

                        const result = await response.json();
                        if (result.success) {
                            // 更新前端显示
                            renderSchedule(result.schedule);
                            alert(`已生成 ${targetDate} 所在周的值班表`);
                        } else {
                            alert('模拟生成失败');
                        }
                    } catch (error) {
                        console.error('模拟生成错误:', error);
                        alert('模拟生成时发生错误');
                    }
                }
            });
        });
    </script>
</body>
</html>